import axios from "axios";
import store from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";

const baseURL = import.meta.env.VITE_BASE_URL;

const service = axios.create({
  baseURL: baseURL,
  timeout: 10000
});

// 请求前的统一处理
service.interceptors.request.use(
  config => {
    // debugger
    // JWT鉴权处理
    if (store.getters["user/token"]) {
      config.headers["Authorization"] = `${store.state.user.token}`;
      // config.headers['token'] = store.state.user.token
    }
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code === 2) {
      return ElMessageBox.confirm(`${res.msg}`, {
        confirmButtonText: "前往登录",
        showClose: false,
        type: "error"
      })
        .then(() => {
          store.dispatch("user/loginOut");
        })
        .catch(() => {
          // catch error
        });
    }
    if (res.code === 0) {
      return res;
    } else {
      showError(res);
      return res;
      // ElMessage({
      //   message: res.msg || res.message || "服务异常",
      //   type: "error",
      //   duration: 3 * 1000
      // });
    }
  },
  error => {
    console.log(error); // for debug
    const badMessage = error.message || error;
    const code = parseInt(
      badMessage
        .toString()
        .replace("Error: Request failed with status code ", "")
    );
    showError({ code, message: badMessage });
    return Promise.reject(error);
  }
);

function showError(error) {
  if (error.code === 403) {
    // to re-login
    store.dispatch("user/loginOut");
  } else {
    ElMessage({
      message: error.msg || error.message || "服务异常",
      type: "error",
      duration: 3 * 1000
    });
  }
}

export default service;
